<?php

class ListTemplateJSON extends ListTemplate {

    private $tJSONRep;

    public function __construct($pRawData) {
        $this->tJSONRep = new JSONDataRepresentation();
        $this->tJSONRep->SetConfigObjectShowed(false);
        if (is_object($pRawData)) {
            $mApp = new Application();
            $tFungsi = new Fungsi();

            $tFungsi->CalibrateArray($pRawData);

            $this->mCurrentURL = $mApp->GetCurrentUrl();
            $this->mRawData = $pRawData;
            $this->mAddAction[Caption] = TEMPLATE_SETTING_LIST_ADD_BUTTON_CAPTION_DEFAULT;

            $this->mAddAction[Auth] = true;
            $this->mEditAction[Auth] = true;
            $this->mDeleteAction[Auth] = true;
            $this->mDetailAction[Auth] = false;
            $this->mUnlockAction[Auth] = false;
            $this->mResetAction[Auth] = false;

            $this->mAddAction[Code] = "add";
            $this->mEditAction[Code] = "edt";
            $this->mDeleteAction[Code] = "del";
            $this->mDetailAction[Code] = "dtl";
            $this->mUnlockAction[Code] = "unl";
            $this->mResetAction[Code] = "rst";
        } else {
            if ($pRawData !== false)
                die();
            else
                $this->mNotExecuteClass = true;
            //ERROR: Bukan merupakan object       
        }
    }

    private function GetButtonConfig($pButton) {
        //check LEVEL LOGIN dengan BUTTON LEVEL AUTH
        $tFungsi = new Fungsi();
        $tButtonConfig= array();
        $tIsAllow = $tFungsi->CheckAuthenticationAllow($pButton[Auth]);

        if ($tIsAllow) {
            $tButtonConfig[$pButton[Code]]= true;

        } else {
            $tButtonConfig[$pButton[Code]]= false;
        }
        $this->tJSONRep->InsertConfig("Action", $tButtonConfig);
    }

    private function GetActionButton() {
        //BUTTON ADD
        $this->GetButtonConfig($this->mAddAction);
        
        //BUTTON DETAIL
        $this->GetButtonConfig($this->mDetailAction);

        //BUTTON UNLOCK
        $this->GetButtonConfig($this->mUnlockAction);

        //BUTTON RESET
        $this->GetButtonConfig($this->mResetAction);

        //BUTTON EDIT
        $this->GetButtonConfig($this->mEditAction);

        //BUTTON DELETE
        $this->GetButtonConfig($this->mDeleteAction);
    }

    public function GenerateList() {
        $tHiddenField = array();

        if (!$this->mNotExecuteClass) {
            $tField = $this->mRawData->GetField();
            $tJmlColDB = count($tField); //JUMLAH TOTAL KOLOM DARI FIELD YANG DIDEKLARASIKAN

            $this->mData = $this->mRawData->ParseSQL($this->GetCurrentPage());

            //  SET CONFIG: HIDDEN FIELD, ACTION BUTTON, TITLE, SUBTITLE
            //////////////////////////////
            if (!empty($tField)) {
                $tHiddenField = $this->GetHiddenField($tField);
                $this->tJSONRep->InsertConfig("HiddenField", $tHiddenField);
            }
            
            $this->GetActionButton();
            
            $this->tJSONRep->InsertConfig("Title", htmlentities($this->mTitle));
            $this->tJSONRep->InsertConfig("SubTitle", htmlentities($this->mSubtitle));
            //////////////////////////////
            
            
            //ERROR MESSAGE
            //////////////////////////////
            if (!empty($_POST[ERROR_SECTION]) && !empty($_POST[ERROR_CODE])) {
                $tErrorMsg = new ErrorMessage();
                $tErrorMsg->SetErrorCode($_POST[ERROR_CODE]);
                $tErrorMsg->SetErrorSection($_POST[ERROR_SECTION]);
                //echo "<div class=\"ErrorMessage-Container\">" . $tErrorMsg->GetErrorMessage() . "</div>";
            }

            $this->PrintParsingData($tJmlColDB);
        }
    }

    /* ========================================================================== */
    /*                              P R I N T                                     */
    /* ========================================================================== */

    private function PrintParsingData($pJmlColDB) {
        // Desc.Fungsi  : Fungsi untuk melakukan set level autentikasi untuk object  untuk object yang ditentukan.
        //                Level autentikasi di deklarasi terlebih dahulu pada DB -> app_user_level
        //                nilai NULL artinya tidak diberikan autentikasi khusus.
        // 
        // PARAMETER 1
        // Nama var     : $pJmlColDB 
        // Tipe var     : INT
        // Def. val     : NOT NULL
        // Desc.        : Nilai jumlah kolom digunakan untuk loop kolom satu per satu untuk retrieval data.
        //                Manggunakan jumlah kolom karena terdapat kolom yang hidden field
        //FUNGSI untuk memparse data dari QUERY dan diubah menjadi bentuk LIST sesuai TEMPLATE
        //CHECK: fika validitas field isset maka terdapat validatas field
        $tFungsi = new Fungsi();
        $tJmlCol = $pJmlColDB;

        if ($this->mIsFieldNumber)
            $tJmlCol++;

        try {
            $no = 1;
            $i = 0;
            $tIndexFieldId = $this->mRawData->GetFieldIndexAsFieldId();
            $tField = $this->mRawData->GetField();
            while ($this->mData->MoveNext()) {
                $this->tJSONRep->CreateNewData();
                $tUnvalidDataOnRow= array();
                $tValiditasData = true;

                ////$tContentData .= "\t<td align=\"center\">" . ($no + ($tCurrentPage * TEMPLATE_SETTING_LIST_PAGING_MAXIMUMPAGE) ) . ".</td>\n";
                //AMBIL NILAI INDEX FIELD UNTUK KEY VALUE, (biasanya merupakan PK)
                //PARSE FIELD DATA
                //Parse data dari Query DB
                for ($x = 0; $x < $pJmlColDB; $x++) {
                    $tOutput = $this->mData->GetRecord($i);
                    $tFieldName = $tField[$x][FieldName];


                    //CHECK: Is Validitas Field Exist?
                    //IF exist, check validity
                    if ($this->mValiditasField && $this->mValiditasPattern && $tValiditasData) {
                        //PERIKSA APAKAH URUTAN SESUAI DENGAN URUTAN FIELD VALIDITAS
                        //GET VALIDITAS VALUE
                        $tValiditas = $tFungsi->CheckValiditasPattern($this->mValiditasPattern, $tOutput);
                        $tValiditasDB = $tOutput[$this->mValiditasField];
                        //echo $tValiditas .' | '.$tValiditasDB.'<br>';
                        if ($tValiditas !== $tValiditasDB) {
                            $tValiditasData = false;
                            array_push($tUnvalidDataOnRow, $i);
                        }

                        //VALIDITAS DEBUG
                        if ($this->mValiditasDebug)
                            echo 'RESULT: ' . $tValiditas . ' | DB: ' . $tValiditasDB . '<br>';
                    }


                    //SET KEY VALUE DARI INDEX FIELD
                    if ($x == $tIndexFieldId) {
                        $tValueFieldId = $tOutput[$x];
                    }

                    if ($this->mFieldUCWords[$x])
                        $this->tJSONRep->InsertData($tFieldName, ucwords(strtolower($tOutput[$x])));
                    else
                        $this->tJSONRep->InsertData($tFieldName, $tOutput[$x]);
                }
                $no++;
                $i++;
            }
            
            //  SET CONFIG: UNVALID DATA ON ROW 
            //////////////////////////////
            if (count($tUnvalidDataOnRow)) {
                $this->tJSONRep->InsertConfig("UnVal", $tUnvalidDataOnRow);
            } else {
                $this->tJSONRep->InsertConfig("UnVal", false);
            }
            //////////////////////////////
            
        } catch (Exception $ex) {
            /* $tContent = "<tr><td colspan=\"" . ($tJmlCol - count($this->mFieldHidden) ) . "\">\n" .
              "Exception Caught: " . $ex->getMessage() . "\n" .
              "<p>Trace: " . $ex->getTraceAsString() . "</p> \n" .
              "</td></tr>"; */
        }
    }

    public function PrintJSON() {
        $this->GenerateList();
        return $this->tJSONRep->PrintJSONDataRepresentation();
    }

}